const express = require('express')
const Result = require('../models/Result')
const { login, findUser } = require('../services/user')
const { md5, decoded } = require('../utils')
const { body, validationResult } = require('express-validator')
const boom = require('boom')
const jwt = require('jsonwebtoken')
const { PWD_SALT, PRIVATE_KEY, JWT_EXPIRED } = require('../utils/constant')

const router = express.Router()

router.post('/login', 
// 在此插入 express-validator 的校验
[
  body('username').isString().withMessage('登录名必须是字符'),
  body('password').isString().withMessage('密码必须是数字')
],
function (req, res, next) {
  // validationResult 的用法就是将 req 传进去
  const err = validationResult(req)
  // 如果 err 不为空，说明校验出错了
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors
    // 将错误信息传递给下一步
    next(boom.badRequest(msg))
  }
  // 如果没有报错，说明校验通过
  else {
    let { username, password } = req.body

    // 对 password 进行加密
    password = md5(`${password}${PWD_SALT}`)
    login(username, password).then(user => {
      if (!user || user.length === 0) {
        new Result('登录失败').fail(res)
      } else {
        const token = jwt.sign(
          { username },
          PRIVATE_KEY,
          { expiresIn: JWT_EXPIRED }
        )
        new Result({ token }, '登录成功').success(res)
      }
    })
  }
})

router.get('/info', function (req, res, next) {
  const decode = decoded(req)
  if (decode && decode.username) {
    findUser(decode.username).then(user => {
      console.log(user, 'user')
      if (user) {
        user.roles = [user.role]
        new Result(user, '用户信息查询成功').success(res)
      } else {
        new Result(user, '用户信息查询失败').fail(res)
      }
    })
  } else {
    new Result(user, '用户信息查询失败').fail(res)
  }
})

module.exports = router